from flask import Flask, request, jsonify
import numpy as np
import pandas as pd
from utils.data_processor import preprocess_input
from utils.model_loader import load_model, get_class_mapping

app = Flask(__name__)

# 加载模型和类别映射
model = load_model()
class_mapping = get_class_mapping()

# 定义中英文字段映射关系
FIELD_MAPPING = {
    'temperature': '温度℃',
    'precipitation': '降水量(mm)',
    'wind_force': '风力(级)',
    'wind_speed': '风速(km/h)',
    'wind_direction_angle': '风向角度(度)',
    'pressure': '气压(hPa)',
    'humidity': '湿度(%)',
    'air_quality': '空气质量',
    'visibility': '能见度(km)',
    'cloud_coverage': '云量%',
    'dew_point': '露点℃',
    'shortwave_radiation': '短波辐射W/m²',
    'direct_radiation': '直接辐射W/m²',
    'scattered_radiation': '散射辐射W/m²',
    'direct_normal_irradiance': '直接正常辐照度W/m²',
    'wind_direction': '风向',
    'weather': '天气'
}


@app.route('/predict', methods=['POST'])
def predict():
    try:
        # 获取请求数据
        data = request.json

        # 验证输入数据
        if not data or 'features' not in data:
            return jsonify({'error': '缺少特征数据'}), 400

        # 转换英文字段名为中文字段名
        translated_features = []
        for feature_dict in data['features']:
            translated_dict = {}
            for en_field, value in feature_dict.items():
                if en_field in FIELD_MAPPING:
                    translated_dict[FIELD_MAPPING[en_field]] = value
                else:
                    # 如果不是映射中的字段，保持原样
                    translated_dict[en_field] = value
            translated_features.append(translated_dict)

        # 数据预处理
        processed_data = preprocess_input(translated_features)

        # 模型预测
        prediction = model.predict(processed_data)
        predicted_class = np.argmax(prediction, axis=1)

        # 转换为天气类别名称
        result = [class_mapping[cls] for cls in predicted_class]

        # 返回结果
        return jsonify({
            'predictions': result,
            'confidence': prediction.max(axis=1).tolist()
        })

    except Exception as e:
        return jsonify({'error': str(e)}), 500


@app.route('/health', methods=['GET'])
def health_check():
    return jsonify({'status': 'healthy', 'message': 'Weather prediction API is running'})


if __name__ == '__main__':
    # 生产环境中应使用Gunicorn等WSGI服务器
    app.run(host='0.0.0.0', port=5000, debug=False)
